#include <iostream>
#include <mysql/mysql.h>
#include <string>
const std::string DB_HOST = "localhost";//从本地host登录，但是对用户的设置可以规定不同的host登录一个是设置，一个是登录地址
const size_t PORT = 3306;
const std::string DB_USER = "zhaoguang";
const std::string DB_PASS = "497380411zg.";
const std::string DB_NAME = "TcpServerdb";

// 检查表是否存在
bool tableExists(MYSQL* conn, const std::string& tableName) {
    std::string query = "SHOW TABLES LIKE '" + tableName + "'";
    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error executing query: " << mysql_error(conn) << std::endl;
        return false;
    }

    MYSQL_RES* result = mysql_store_result(conn);
    if (!result) {
        std::cerr << "Error storing result: " << mysql_error(conn) << std::endl;
        return false;
    }

    bool exists = (mysql_num_rows(result) > 0);
    mysql_free_result(result);
    return exists;
}

// 创建 User 表
bool createUserTable(MYSQL* conn) {
    std::string query = R"(
        CREATE TABLE User (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL
        )
    )";

    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error creating table: " << mysql_error(conn) << std::endl;
        return false;
    }
    return true;
}

// 插入用户名和密码
bool insertUser(MYSQL* conn, const std::string& name, const std::string& password) {
    std::string query = "INSERT INTO User (name, password) VALUES ('" + name + "', '" + password + "')";
    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error inserting user: " << mysql_error(conn) << std::endl;
        return false;
    }
    return true;
}

int main() {
    printf("mysql client Version: %s\n", mysql_get_client_info());
    // 初始化 MySQL 连接    
    MYSQL* conn = mysql_init(nullptr);
    if (!conn) {
        std::cerr << "mysql_init() failed" << std::endl;
        return EXIT_FAILURE;
    }
    // 连接到 MySQL 数据库
    if (!mysql_real_connect(conn, DB_HOST.c_str(), DB_USER.c_str(), DB_PASS.c_str(), DB_NAME.c_str(), PORT, nullptr, 0)) {
        std::cerr << "mysql_real_connect() failed: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return EXIT_FAILURE;
    }
    std::cout << "Connected to MySQL server." << std::endl;
    // 检查 User 表是否存在
    if(!tableExists(conn,"User")){
        std::cout << "User table does not exist. Creating it..." << std::endl;
        if (!createUserTable(conn)) {
            std::cerr << "Failed to create User table." << std::endl;
            mysql_close(conn);
            return EXIT_FAILURE;
        }
        std::cout << "User table created successfully." << std::endl;
        // 插入用户名和密码
        insertUser(conn, "admin", "123456");    
    } else {
        std::cout << "User table already exists." << std::endl;     
    }  
    
    return 0;
}